package com.heima.handler;


import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    public static final String UNKNOWN_ERROR = "未知错误";
    public static final String ALREADY_EXISTS = "已存在";

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
/*    @ExceptionHandler
    public String exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return ex.getMessage();
    }*/
    @ExceptionHandler
    public String exceptionHandler(SQLIntegrityConstraintViolationException ex){
        //Duplicate entry 'zhangsan' for key 'employee.idx_username'
        String message = ex.getMessage();
        if(message.contains("Duplicate entry")){
            String[] split = message.split(" ");
            String username = split[2];
            String msg = username + ALREADY_EXISTS;
            return msg;
        }else{
            return UNKNOWN_ERROR;
        }
    }
}
